<template>
  <div class="enterprise-create-wrapper">
    <HomeNavBar />
    
    <div class="enterprise-create-container">
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <h2>创建企业</h2>
            <el-button :icon="ArrowLeft" text @click="goBack">返回</el-button>
          </div>
        </template>

        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="create-form"
        >
          <el-form-item label="企业名称" prop="enterpriseName">
            <el-input
              v-model="form.enterpriseName"
              placeholder="请输入企业名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="企业简介" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入企业简介"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="企业Logo">
            <el-upload
              class="upload-demo"
              :on-change="handleLogoChange"
              :on-remove="handleLogoRemove"
              :before-upload="beforeLogoUpload"
              :limit="1"
              accept="image/*"
              :auto-upload="false"
              list-type="picture"
            >
              <el-button type="primary">选择Logo</el-button>
              <template #tip>
                <div class="el-upload__tip">支持jpg/png格式，建议大小200x200px</div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="企业图片">
            <el-upload
              class="upload-demo"
              :on-change="handleImageChange"
              :on-remove="handleImageRemove"
              :before-upload="beforeImageUpload"
              :limit="1"
              accept="image/*"
              :auto-upload="false"
              list-type="picture"
            >
              <el-button type="primary">选择企业图片</el-button>
              <template #tip>
                <div class="el-upload__tip">支持jpg/png格式，建议大小1200x600px</div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="福利待遇">
            <el-input
              v-model="form.benefits"
              type="textarea"
              :rows="3"
              placeholder="请输入福利待遇，每行一项"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="submitting" @click="submitForm">
              创建企业
            </el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import HomeNavBar from '@/components/HomeNavBar.vue'
import instance from '@/utils/request'
import useStore from '@/store'

const router = useRouter()
const store = useStore()

const formRef = ref(null)
const submitting = ref(false)
const form = ref({
  enterpriseName: '',
  description: '',
  logoFile: null, // 存储文件对象
  imageFile: null, // 存储文件对象
  benefits: ''
})

const rules = {
  enterpriseName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { min: 2, max: 100, message: '企业名称长度在2到100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入企业简介', trigger: 'blur' }
  ]
}

// Logo文件选择
const handleLogoChange = (file) => {
  form.value.logoFile = file.raw
}

const handleLogoRemove = () => {
  form.value.logoFile = null
}

const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 企业图片文件选择
const handleImageChange = (file) => {
  form.value.imageFile = file.raw
}

const handleImageRemove = () => {
  form.value.imageFile = null
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    submitting.value = true
    try {
      const formData = new FormData()
      formData.append('enterpriseName', form.value.enterpriseName)
      formData.append('description', form.value.description)
      formData.append('benefits', form.value.benefits || '')
      if (form.value.logoFile) {
        formData.append('logo', form.value.logoFile)
      }
      if (form.value.imageFile) {
        formData.append('image', form.value.imageFile)
      }

      const response = await instance.request({
        method: 'POST',
        url: '/enterprises',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (response.code === 0) {
        ElMessage.success('企业创建成功！')
        // 更新用户信息
        store.app.updateRole('enterprise')
        // 跳转到企业列表
        router.push('/enterprises')
      } else {
        ElMessage.error(response.msg || '创建失败')
      }
    } catch (error) {
      console.error('创建企业失败:', error)
      ElMessage.error('创建企业失败，请重试')
    } finally {
      submitting.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  form.value = {
    enterpriseName: '',
    description: '',
    logoFile: null,
    imageFile: null,
    benefits: ''
  }
}

// 返回
const goBack = () => {
  router.push('/enterprises')
}
</script>

<style lang="scss" scoped>
.enterprise-create-wrapper {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 30px 20px;
}

.enterprise-create-container {
  max-width: 900px;
  margin: 0 auto;
}

.form-card {
  border-radius: 12px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h2 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.create-form {
  padding: 20px 0;

  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.upload-demo {
  :deep(.el-upload__tip) {
    color: #909399;
    font-size: 12px;
    margin-top: 8px;
  }
}
</style>
